package com.dtagri.fjwlw.ui;

import java.io.UnsupportedEncodingException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.android.nvssdklib.NvssdkAPI;
import com.android.nvssdklib.PNVS_FILE_DATA;
import com.android.nvssdklib.PNVS_FILE_QUERY;
import com.dtagri.fjwlw.R;
import com.dtagri.fjwlw.bean.tdvideo.cls_DateTime;
import com.dtagri.fjwlw.ui.tdvideo.CLS_VideoViewController;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.DatePickerDialog;
import android.app.TimePickerDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Configuration;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.ExpandableListAdapter;
import android.widget.ExpandableListView;
import android.widget.RelativeLayout;
import android.widget.SeekBar;
import android.widget.SimpleAdapter;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ExpandableListView.OnGroupCollapseListener;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.Toast;

/**
 * 天地伟业
 * @author Administrator
 *
 */
public class Show_Download_View extends Activity {
	//业务
	private int m_ilogonID,m_iChannelNum;
	private String m_strHostIP;
	private CLS_VideoViewController m_cls_VideoViewController;
	public Handler messageHandler;
	
	private static  int m_CONSTPageSize = 20;
	private int m_iPageNO, m_ihasRecvNum;
	private int[] m_iTotalFile;
	private int[] m_iDownloadId;
	private List<String> m_listStrFileName;
	// date and time
    private int mYear,mMonth,mDay,mHour,mMinute;
    private cls_DateTime m_startDateTime,m_endDateTime;
    static final int TIME_DIALOG_ID = 0;
    static final int DATE_DIALOG_ID = 1;
    
	private List<Map<String, Object>> m_listFileName;
	private SimpleAdapter Sadapter;
	private ListView m_listQueryResult;
	private TextView m_tvChannelName;
	
	private Button m_btnStartDate,m_btnStartTime,m_btnEndDate,m_btnEndTime;
	private int m_ibtnPressID;
	private ImageButton m_btnQuery,m_btnBackQuery;
	private RelativeLayout m_Layout_Query;
	private LinearLayout m_Layout_Query_Menu,m_Layout_Back,m_Layout_Result,m_Layout_Video_btn,m_Layout_Filename;
	
	private String m_strFileName;
	
	public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.video_download_view_show);
        
        Looper looper = Looper.myLooper();    
        messageHandler = new MessageHandler(looper);
        
        initVariable();  
        
        m_startDateTime = new cls_DateTime();
        m_endDateTime = new cls_DateTime();
        final Calendar c = Calendar.getInstance();
        mYear = c.get(Calendar.YEAR);
        mMonth = c.get(Calendar.MONTH);
        mDay = c.get(Calendar.DAY_OF_MONTH);
        mHour = c.get(Calendar.HOUR_OF_DAY);
        mMinute = c.get(Calendar.MINUTE);
        m_ibtnPressID = 0;
        updateDisplay();
	}
	@Override   

	public void onConfigurationChanged(Configuration newConfig){
		//Toast.makeText(this, "...切换",Toast.LENGTH_SHORT).show();
		 super.onConfigurationChanged(newConfig);
	}
	
	private static String pad(int c) {
	        if (c >= 10)
	            return String.valueOf(c);
	        else
	            return "0" + String.valueOf(c);
	}
	private String clsDateTimeToString(cls_DateTime dt) {
		
		StringBuilder str =  new StringBuilder()
                    .append(dt.getYear()).append("-")
                    .append(pad(dt.getMonth())).append("-")
                    .append(pad(dt.getDay())).append(" ")
                    .append(pad(dt.getHour())).append(":")
                    .append(pad(dt.getMinute())).append(":00");
		return str.toString();
    } 
	private void updateDisplay() {
		// Month is 0 based so add 1
		int itempMonth = mMonth + 1;
		StringBuilder sbDate = new StringBuilder()					        
					        .append(mYear).append("-")
					        .append(pad(itempMonth)).append("-")
					        .append(pad(mDay));
		StringBuilder sbTime = new StringBuilder()	 
					        .append(pad(mHour)).append(":")
					        .append(pad(mMinute)).append(":00");
		if(m_ibtnPressID == 0)
		{
			m_btnStartDate.setText(sbDate);
			m_btnEndDate.setText(sbDate);
			//m_btnStartTime.setText(sbTime);
			//m_btnEndTime.setText(sbTime);
			m_startDateTime.setYear(mYear);
			m_startDateTime.setMonth(itempMonth);
			m_startDateTime.setDay(mDay);
			m_startDateTime.setHour(0);
			m_startDateTime.setMinute(0);
			
			m_endDateTime.setYear(mYear);
			m_endDateTime.setMonth(itempMonth);
			m_endDateTime.setDay(mDay);
			m_endDateTime.setHour(23);
			m_endDateTime.setMinute(59);
		}
		else if(m_btnStartDate.getId()==m_ibtnPressID)
		{
			m_startDateTime.setYear(mYear);
			m_startDateTime.setMonth(itempMonth);
			m_startDateTime.setDay(mDay);
			m_btnStartDate.setText(sbDate);
		}
		else if(m_btnEndDate.getId()==m_ibtnPressID)
		{
			m_endDateTime.setYear(mYear);
			m_endDateTime.setMonth(itempMonth);
			m_endDateTime.setDay(mDay);
			m_btnEndDate.setText(sbDate);
		}
		else if(m_btnStartTime.getId()==m_ibtnPressID)
		{
			m_startDateTime.setHour(mHour);
			m_startDateTime.setMinute(mMinute);
			m_btnStartTime.setText(sbTime);
		}
		else if(m_btnEndTime.getId()==m_ibtnPressID)
		{
			m_endDateTime.setHour(mHour);
			m_endDateTime.setMinute(mMinute);
			m_btnEndTime.setText(sbTime);
		}
    }
	@Override
    protected Dialog onCreateDialog(int id) {
        switch (id) {
            case TIME_DIALOG_ID:
                return new TimePickerDialog(this,
                        mTimeSetListener, mHour, mMinute, true);
            case DATE_DIALOG_ID:
                return new DatePickerDialog(this,
                            mDateSetListener,
                            mYear, mMonth, mDay);
        }
        return null;
    }

    @Override
    protected void onPrepareDialog(int id, Dialog dialog) {
        switch (id) {
            case TIME_DIALOG_ID:
                ((TimePickerDialog) dialog).updateTime(mHour, mMinute);
                break;
            case DATE_DIALOG_ID:
                ((DatePickerDialog) dialog).updateDate(mYear, mMonth, mDay);
                break;
        }
    }  
    
    private DatePickerDialog.OnDateSetListener mDateSetListener =
        new DatePickerDialog.OnDateSetListener() {

            public void onDateSet(DatePicker view, int year, int monthOfYear,
                    int dayOfMonth) {
                mYear = year;
                mMonth = monthOfYear;
                mDay = dayOfMonth;
                updateDisplay();
            }
        };

        private TimePickerDialog.OnTimeSetListener mTimeSetListener =
        new TimePickerDialog.OnTimeSetListener() {

            public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
                mHour = hourOfDay;
                mMinute = minute;
                updateDisplay();
            }
        };

	private void initVariable()
	{
		m_cls_VideoViewController = CLS_VideoViewController.GetInstance();
		m_cls_VideoViewController.Registe(Show_Download_View.this);
		m_iPageNO = 0;
		m_iTotalFile = new int[1]; 
		m_ihasRecvNum = 0;
		
		m_ilogonID = m_cls_VideoViewController.GetCurrentCLS_Channel().GetLogonID();
		m_iChannelNum = m_cls_VideoViewController.GetCurrentCLS_Channel().GetChannelNum();
		m_strHostIP = m_cls_VideoViewController.GetCurrentCLS_Channel().GetHostEntity().getConnectIP();
		
		//====================================
        m_listQueryResult = (ListView)this.findViewById(R.id.Result_List);
        m_tvChannelName = (TextView)this.findViewById(R.id.current_channel_name);
        
        m_btnStartDate = (Button)this.findViewById(R.id.startPickDate);
        m_btnStartTime = (Button)this.findViewById(R.id.startPickTime);
        m_btnEndDate = (Button)this.findViewById(R.id.endPickDate);
        m_btnEndTime = (Button)this.findViewById(R.id.endPickTime);
        
		m_btnQuery = (ImageButton)this.findViewById(R.id.Query_Rec_File_Btn);
		m_btnBackQuery = (ImageButton)this.findViewById(R.id.Query_Rec_File_Back_Btn);
		m_Layout_Query_Menu = (LinearLayout)this.findViewById(R.id.Query_Rec_File_Layout);
		m_Layout_Back = (LinearLayout)this.findViewById(R.id.Query_Rec_File_Back_Layout);
		
		m_Layout_Query = (RelativeLayout)this.findViewById(R.id.Rec_Query_layout);
		m_Layout_Result = (LinearLayout)this.findViewById(R.id.query_result_layout);

		m_btnStartDate.setOnClickListener(btnClickListener);
		m_btnStartTime.setOnClickListener(btnClickListener);
		m_btnEndDate.setOnClickListener(btnClickListener);
		m_btnEndTime.setOnClickListener(btnClickListener);
		
		m_btnQuery.setOnClickListener(btnClickListener);		
		m_btnBackQuery.setOnClickListener(btnClickListener);
        
        m_listQueryResult.setOnItemClickListener(listener);

	}

	private OnClickListener btnClickListener = new OnClickListener() {
		
		public void onClick(View v) {
			// TODO Auto-generated method stub
			m_ibtnPressID = v.getId();
			switch(v.getId())
			{
			case R.id.startPickDate:
				showDialog(DATE_DIALOG_ID);
				break;
			case R.id.startPickTime:
				mHour = 0;
				mMinute = 0;
				showDialog(TIME_DIALOG_ID);
				break;
			case R.id.endPickDate:
				showDialog(DATE_DIALOG_ID);
				break;
			case R.id.endPickTime:
				mHour = 23;
				mMinute = 59;
				showDialog(TIME_DIALOG_ID);
				break;
			case R.id.Query_Rec_File_Btn:
				StartQueryFile();
				break;
			case R.id.Query_Rec_File_Back_Btn:
				finish();
				break;
			default:
				break;
			}
		}
	};
	private void StartQueryFile(){
		java.text.DateFormat df = new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		Calendar cStart = Calendar.getInstance();
		Calendar cEnd = Calendar.getInstance();
		Date dtime;
		try {
			dtime = df.parse(clsDateTimeToString(m_startDateTime));
			cStart.setTime(dtime);
			dtime = df.parse(clsDateTimeToString(m_endDateTime));
			cEnd.setTime(dtime);
			
			int result=cStart.compareTo(cEnd);
			if(result>=0){
				Toast.makeText(Show_Download_View.this, R.string.Query_Rec_StopLittleStart,Toast.LENGTH_SHORT).show();
				return;
			}

			int iret = NvssdkAPI.GetInstance().NetClient_NetFileQuery(m_ilogonID,  QueryFile(m_iPageNO));
			if(iret != 0){
				Log.i("Download","NetClient_NetFileQuery iret "+iret);
				Toast.makeText(Show_Download_View.this, "查询失败",Toast.LENGTH_SHORT).show();
			}
			
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}
	
	private List<Map<String, Object>> getData() {  
        List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();  
        Map<String, Object> map = null;
        for(int i=0;i<m_listStrFileName.size();i++){
        	map = new HashMap<String, Object>();  
            map.put("filename",m_listStrFileName.get(i));
            list.add(map);
        }
        return list;  
    } 
	private void showQueryResult(){
		if(m_listFileName==null){
			m_listFileName = getData();
			//return ;  
		}
		Sadapter = new SimpleAdapter(this,m_listFileName,R.layout.video_record_query_result_item,
        		new String[]{"filename"},new int[]{R.id.filename}); 

		m_listQueryResult.setAdapter(Sadapter);
		
		
		m_tvChannelName.setText(m_strHostIP+"-channel "+m_iChannelNum);
	
		m_Layout_Query.setVisibility(View.GONE);
		m_Layout_Result.setVisibility(View.VISIBLE);
	}
	
	OnItemClickListener listener = new OnItemClickListener(){
		public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
				long arg3) {
			Map<String, Object> map = (Map<String, Object>)m_listQueryResult.getItemAtPosition(arg2);
			m_strFileName = map.get("filename").toString();
			Toast.makeText(Show_Download_View.this, "准备下载"+m_strFileName,Toast.LENGTH_SHORT).show();
			m_iDownloadId  = new int[1];
			int iRet = NvssdkAPI.GetInstance().NetClient_NetFileDownloadFileEx(m_iDownloadId,m_ilogonID,m_strFileName,"/sdcard/NetVideoBrowser/"+m_strFileName);
			if(iRet != 0){
				Toast.makeText(Show_Download_View.this, "图片下载失败",Toast.LENGTH_SHORT).show();
			}
		}
    };

    private PNVS_FILE_QUERY QueryFile(int iPageNo){
    	PNVS_FILE_QUERY pnvsFileQuery = new PNVS_FILE_QUERY();
		pnvsFileQuery.iChannel = m_iChannelNum;
		pnvsFileQuery.iDevType = 0xFF;
		pnvsFileQuery.iFiletype = 2;//文件类型，0-所有， 1-音视频文件， 2-图片
		pnvsFileQuery.iPageNo = iPageNo;
		pnvsFileQuery.iPageSize = m_CONSTPageSize;
		pnvsFileQuery.iType = 1;//手动录像//录像类型 0xFF-全部，1-手动录像，2-定时录像，3-报警录像
		pnvsFileQuery.struStartTime.iDay = m_startDateTime.getDay();
		pnvsFileQuery.struStartTime.iHour = m_startDateTime.getHour();
		pnvsFileQuery.struStartTime.iMinute = m_startDateTime.getMinute();
		pnvsFileQuery.struStartTime.iMonth = m_startDateTime.getMonth();
		pnvsFileQuery.struStartTime.iSecond = 0;
		pnvsFileQuery.struStartTime.iYear = m_startDateTime.getYear();

		pnvsFileQuery.struStopTime.iDay = m_endDateTime.getDay();
		pnvsFileQuery.struStopTime.iHour = m_endDateTime.getHour();
		pnvsFileQuery.struStopTime.iMinute = m_endDateTime.getMinute();
		pnvsFileQuery.struStopTime.iMonth = m_endDateTime.getMonth();
		pnvsFileQuery.struStopTime.iSecond = 0;
		pnvsFileQuery.struStopTime.iYear = m_endDateTime.getYear();
		pnvsFileQuery.strOtherQuery = "";  
		
		return pnvsFileQuery;
    }
    
    public boolean onKeyDown(int keyCode, KeyEvent event)
	{
		if(keyCode == KeyEvent.KEYCODE_BACK)
		{	
			if(m_Layout_Result.getVisibility() == View.VISIBLE)
			{
				m_Layout_Query.setVisibility(View.VISIBLE);
				m_Layout_Result.setVisibility(View.GONE);
				m_listFileName = null;
				m_listStrFileName = null;
				m_iPageNO = 0;
				m_iTotalFile = new int[1]; 
				m_ihasRecvNum = 0;
			}
			else if(m_Layout_Query.getVisibility() == View.VISIBLE)
			{
				finish();
			}
			return true;
		}
		return super.onKeyDown(keyCode, event);
	}
    
//子类化一个Handler   
    
    class MessageHandler extends Handler {   
  
        public MessageHandler(Looper looper) {   
  
            super(looper); 
        }   
  
        @Override  
  
        public void handleMessage(Message msg) {   
        	int iswitch = msg.arg1;
        	int idownloadId = msg.arg2;
        	switch(iswitch)
        	{
        	case 18://图片查询结束
        		int[] cur   = new int[1];
    			if (NvssdkAPI.GetInstance().NetClient_NetFileGetFileCount(m_ilogonID, m_iTotalFile, cur) != 0) {
    				Log.i("Download","NetClient_NetFileGetFileCount Error");
    				break;
    			}
    			if(m_iTotalFile[0] <= 0){
    				Toast.makeText(Show_Download_View.this, "查询条数为0",Toast.LENGTH_SHORT).show();
    				break;
    			}
    			if(m_listStrFileName ==null){
    				m_listStrFileName = new ArrayList<String>(m_iTotalFile[0]);
    			}
    			for(int i=0;i<cur[0]&& i < m_CONSTPageSize;i++){
    				PNVS_FILE_DATA pnvsFileQuery = new PNVS_FILE_DATA();  				
    				NvssdkAPI.GetInstance().NetClient_NetFileGetQueryfile(m_ilogonID,i,pnvsFileQuery);
    				//Log.i("Download",pnvsFileQuery.strFileName+" "+pnvsFileQuery.strFileName);
    				
    				m_listStrFileName.add(pnvsFileQuery.strFileName);
    				m_ihasRecvNum++;
    			}
    			if(m_ihasRecvNum<m_iTotalFile[0]){
    				Log.i("Download",m_iTotalFile[0]+"of "+m_ihasRecvNum);
    				NvssdkAPI.GetInstance().NetClient_NetFileQuery(m_ilogonID,  QueryFile(++m_iPageNO));
    			}
    			else {
    				showQueryResult();
    			}
    			
        		break;
        	case 19://图片下载完毕
        		NvssdkAPI.GetInstance().NetClient_NetFileStopDownloadFile(idownloadId);
        		Toast.makeText(Show_Download_View.this, "图片下载成功",Toast.LENGTH_SHORT).show();
        		break;
        	case 20://图片下载失败
        		NvssdkAPI.GetInstance().NetClient_NetFileStopDownloadFile(idownloadId);
        		Toast.makeText(Show_Download_View.this, "图片下载失败",Toast.LENGTH_SHORT).show();
        		break;
        	default:
        		break;
        	}
        }   
    } 
}
